# -*- coding: iso-8859-2 -*-

import os

from authorshipanalyzer.file import Path
from authorshipanalyzer.utils import sortDictionaryByValue

class SlotSizeExperiment:
    '''
    Tracking experiment of slot size
    '''
    
    def __init__(self, size = 15):
        '''
        @param ranks: dict<msg_num, rank_num>
        @param proc: dict<msg_num, proc_similarity>
        '''
        self.proc = {}
        self.ranks = {}
        
        for i in range(0, size + 1):
            self.ranks[i] = []
            self.proc[i] = []
                        
    def addResult(self, label, uAuthor, result):
        '''
        Resolve result from classifier output and save values
        '''
        sortedResult = sortDictionaryByValue(result)
        
        similarity = 0.0
        if result.has_key(uAuthor):
            similarity = result[uAuthor]          
        self.proc[label].append(similarity)
        
        rank = 0
        for singleRes in sortedResult:
            rank += 1
            if singleRes[0] == uAuthor:
                break
            
        self.ranks[label].append(rank)
        
    def printResults(self):
        '''
        Print result of comparison
        '''        
        # print procentage similarity result
        output = os.path.join(Path.getResourceDir(), "size", "size_proc.dat")
        outputFile = file(output, "w")
        
        for msgNum, measures in self.proc.items():
            sum = 0.0
            for measure in measures:
                sum += measure
            
            avgProc = 0.0
            if sum > 0.0:
                avgProc = sum / float(len(measures))
                
            outputFile.write("%d %s\n" % (msgNum, avgProc) )
            
        outputFile.flush()
        outputFile.close()
        
        # print rank results
        output = os.path.join(Path.getResourceDir(), "size", "size_rank.dat")
        outputFile = file(output, "w")  
             
        for i in range(len(self.ranks)):
            rankList = self.ranks[i]
            
            sum = 0.0
            for rank in rankList:
                sum += rank
                
            avgRank = 0.0
            if sum > 0.0:
                avgRank = sum / float(len(rankList))
            outputFile.write("%d %s\n" % (i, avgRank) )      
            
        outputFile.flush()
        outputFile.close()